<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Models\Shop\Cart;

class CartController extends Controller
{
    /**
     * 购物车首页
     */
    public function index()
    {
        $user = JWTAuth::parseToken()->authenticate(); //获取用户信息
        $carts = Cart::with('product')->where('customer_id', $user->id)->get();
        $count = Cart::count_cart($carts);
        return response()->json(compact('carts', 'count'));
    }

    /**
     * 添加商品到购物车
     */
    public function store(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate(); //获取用户信息
        $product_id = $request->product_id;
        $customer_id = $user->id;

        $cart = Cart::where('product_id', $product_id)->where('customer_id', $customer_id)->first();
        //判断购物车有没有该商品，有则数量加一，没有添加商品
        if ($cart) {
            Cart::where('id', $cart->id)->increment('num');
        } else {
            Cart::create([
                'product_id' => $product_id,
                'customer_id' => $customer_id,
            ]);
        }

        //添加成功后重新查询购物车
        $carts = Cart::with('product')->where('customer_id', $user->id)->get();
        $count = Cart::count_cart($carts);
        return response()->json(compact('carts', 'count'));
    }

    /**
     * 改变商品数量
     */
    public function change_num(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate(); //获取用户信息
        if ($request->type == 'inc') {
            Cart::where('id', $request->cart_id)->increment('num');
        } else {
            Cart::where('id', $request->cart_id)->decrement('num');
        }
        //新增，减少商品数量成功后重新查询购物车
        $carts = Cart::with('product')->where('customer_id', $user->id)->get();
        $count = Cart::count_cart($carts);
        return response()->json(compact('carts', 'count'));
    }

    /**
     * 删除商品
     */
    public function destroy(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate(); //获取用户信息
        Cart::destroy($request->cart_id);

        //删除商品数量成功后重新查询购物车
        $carts = Cart::with('product')->where('customer_id', $user->id)->get();
        $count = Cart::count_cart($carts);
        return response()->json(compact('carts', 'count'));
    }

}
